package service

import (
	"errors"
	"fmt"
	"io"
	"math/rand"
	"os"
	"time"
)

type AttachService struct {
	FileType string
	SrcFile io.Reader
	DstFile io.Writer
	DstFileName string
	Dir string
	Url string
}

const AttachDir = "./media/"
const AttachUrl = "/media/"

func init()  {
	os.MkdirAll(AttachDir, os.ModePerm)
}

func  (s *AttachService) generateNewFileName()  {
	s.DstFileName = fmt.Sprintf("%d%04d%s",time.Now().Unix(), rand.Int31(), s.FileType)
}

func  (s *AttachService) createNewFile() error  {
	s.generateNewFileName()

	if _, err := os.Stat(s.Dir); err != nil {
		err := os.MkdirAll(s.Dir, os.ModePerm)
		if err != nil {
			return err
		}
	}
	file, err := os.Create(s.Dir + s.DstFileName)
	if err != nil {
		return err
	}
	s.DstFile = file
	_, err = io.Copy(s.DstFile, s.SrcFile)
	return err
}

func (s *AttachService) Dispath() (string, error)  {
	switch s.FileType {
	case FILE_TYPE_JPG:
		fallthrough
	case FILE_TYPE_PNG:
		fallthrough
	case FILE_TYPE_GIF:
		fallthrough
	case FILE_TYPE_JPEG:
		s.Dir = AttachDir + "images/"
		s.Url = AttachUrl + "images/"
	case FILE_TYPE_MP3:
		s.Dir = AttachDir + "audios/"
		s.Url = AttachUrl + "audios/"
	case FILE_TYPE_MP4:
		s.Dir = AttachDir + "videos/"
		s.Url = AttachUrl + "videos/"
	default:
		return "", errors.New("不支持此格式")
	}

	err := s.createNewFile()

	s.Url = s.Url + s.DstFileName
	return  s.Url, err
}

const (
	FILE_TYPE_JPG = ".jpg"
	FILE_TYPE_PNG = ".png"
	FILE_TYPE_GIF = ".gif"
	FILE_TYPE_JPEG = ".jpeg"
	FILE_TYPE_MP3 = ".mp3"
	FILE_TYPE_MP4 = ".mp4"
)